package com.example.langchain4jdemo.ModelController;

import com.example.langchain4jdemo.model.ApiResult;
import com.example.langchain4jdemo.modelService.ModelService;
import dev.langchain4j.data.image.Image;
import jakarta.annotation.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;

@RestController
@RequestMapping("/ai")
public class Controller {

    @Resource
    ModelService modelService;


    /**
     * 图片识别接口
     * @param image  上传的图片
     * @param prompt 提示词
     * @return 返回识别信息
     * @throws IOException
     */
    @PostMapping("image")
    public ApiResult<String> plantRecognition(MultipartFile image, String prompt) throws IOException {
        //参数判空检查
        try {
            if (image == null) {
                return ApiResult.fail("请上传图片");
            }
            if (prompt == null || prompt.isEmpty()) {
                prompt = "请描述图片信息";
            }
            String base64Data = Base64.getEncoder().encodeToString(image.getBytes());
            Image img = Image.builder().base64Data(base64Data).build();
            return ApiResult.success(modelService.recognition(img, prompt));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 有记忆对话
     * @param prompt
     * @return
     */
    @PostMapping("/chat/Memory")
    public ApiResult<String> chat(String prompt) {
        try {
            if(prompt==null){
                return ApiResult.fail("请输入提示词");
            }
            String string = modelService.chatWithMemory(prompt);
            return ApiResult.success(string);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 无记忆对话
     * @param prompt
     * @return
     */
    @PostMapping("/chat/noMemory")
    public ApiResult<String> chatNoMemory(String prompt){
        String response = modelService.chatNoMemory(prompt);
        return ApiResult.success(response);
    }
}
